package com.yipin.neimeng.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author feiniu
 * @date 2024/4/1 17:15
 */
public class Md5Util {
    public static String encryptMD5(String input) {
        try {
            // Create MD5 Digest
            MessageDigest md = MessageDigest.getInstance("MD5");
            // Digest the input
            md.update(input.getBytes());
            // Get the hash's bytes
            byte[] digest = md.digest();
            // This bytes[] has hash
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 not supported", e);
        }
    }

    public static String encryptMD5ToUppercase(String input) {
        try {
            // Create MD5 Digest
            MessageDigest md = MessageDigest.getInstance("MD5");
            // Digest the input
            md.update(input.getBytes());
            // Get the hash's bytes
            byte[] digest = md.digest();
            // This bytes[] has hash
            return bytesToHex(digest).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 not supported", e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
